<template>
  <div class="history-score">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="title"
    ></white-header>
    <div class="head-charts">
      <div class="charts-title">
        历史成绩
      </div>
      <div class="charts-menu">
        <div
          :class="['menu-item', menuType == 1 ? 'selected' : '']"
          @click="menuHandle(1)"
        >
          近一周
        </div>
        <div
          :class="['menu-item', menuType == 2 ? 'selected' : '']"
          @click="menuHandle(2)"
        >
          近一月
        </div>
        <div
          :class="['menu-item', menuType == 3 ? 'selected' : '']"
          @click="menuHandle(3)"
        >
          近一年
        </div>
      </div>
      <canvas id="myChart" style="width:7.2rem;height:4.992rem;"></canvas>
    </div>
    <div class="test-record">
      <div class="record-item" v-for="(item, index) in donePaperData" :key="index">
        <span class="record-time">{{ item.time }}</span>
        <span class="record-fraction">{{ item.score }}分</span>
        <span class="record-status">
          <span
            style="color: #f99797;"
            v-if="
              item &&
                item.questionDonePaperVO &&
                item.questionDonePaperVO.score <
                  item.questionDonePaperVO.passScore
            "
            >不及格</span
          >
          <span style="color: var(--theme-color);" v-else>及格</span>
        </span>
        <span
          class="record-review"
          @click="testReview(item.questionDonePaperVO)"
          >考试回顾<img src="/img/mobile/right-icon.png"
        /></span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getHistoryRecord } from "~/api/v2-question-bank/question-bank.js";
export default {
  components: {
    WhiteHeader
  },
  scrollToTop: true,
  data() {
    return {
      title: "历史成绩",
      data: [],
      menuType: 1,
      chart: null,
      donePaperData:[],
      timeQuantum:[],
      chartData:[],
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_loading(state) {
        return state.is_loading;
      },
      shallowColor(state) {
        return state.web_info.THEME_COLOR + "32";
      },
      chartColor(state) {
        return state.web_info.THEME_COLOR;
      }
    })
  },
  watch: {
    chartColor(newName, oldName) {
      this.menuHandle(1);
    }
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    menuHandle(type) {
      this.menuType = type;


      // 获取时间段的每一天<---
      if(type == 1){
        this.timeQuantum = this.getDateDay("week");
        this.chartData = this.formatEveryDay(this.timeQuantum[0], this.timeQuantum[1]);
      }else if(type == 2){
        this.timeQuantum = this.getDateDay("month");
        this.chartData = this.formatEveryDay(this.timeQuantum[0], this.timeQuantum[1]);
      }else if(type == 3){
        this.timeQuantum = this.getDateDay("year");
        this.chartData = this.formatEveryDay(this.timeQuantum[0], this.timeQuantum[1]);
      }
      // 获取时间段的每一天--->


      this.getHistoryRecord();
    },
    //获取时间段的起始时间和结束时间
    getDateDay(type) {
      const end = new Date();
      if (type == "week") {
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        const dateList = [this.formatDate(start), this.formatDate(end)];
        return dateList;
      } else if (type == "month") {
        let year = new Date().getFullYear();
        let month = new Date().getMonth() + 1;
        let date = new Date().getDate();
        if (month == 1) {
          month = 12;
          year = year - 1;
        } else {
          month = month - 1;
        }
        if (month < 10) {
          month = "0" + month;
        }
        if (date < 10) {
          date = "0" + date;
        }
        const dateList = [
          year + "-" + month + "-" + date,
          this.formatDate(end)
        ];
        return dateList;
      } else if (type == "year") {
        let year = new Date().getFullYear() - 1;
        let month = new Date().getMonth() + 1;
        let date = new Date().getDate();
        if (month < 10) {
          month = "0" + month;
        }
        if (date < 10) {
          date = "0" + date;
        }
        const dateList = [
          year + "-" + month + "-" + date,
          this.formatDate(end)
        ];
        return dateList;
      }
    },
    formatDate(value) {
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let date = value.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (date < 10) {
        date = "0" + date;
      }
      return year + "-" + month + "-" + date;
    },
    //获取时间段的每一天
    formatEveryDay(start, end) {
      let dateList = [];
      var startTime = this.getDate(start);
      var endTime = this.getDate(end);

      while (endTime.getTime() - startTime.getTime() >= 0) {
        var year = startTime.getFullYear();
        var month =
          startTime.getMonth() + 1 < 10
            ? "0" + (startTime.getMonth() + 1)
            : startTime.getMonth() + 1;
        var day =
          startTime.getDate().toString().length == 1
            ? "0" + startTime.getDate()
            : startTime.getDate();
        // dateList.push(year + "-" + month + "-" + day);
        dateList.push({
          date: year + "-" + month + "-" + day,
          value: 0,
          tag: 0
          // value: Math.floor(Math.random() * (100 - 0) + 0),
          // tag: Math.random() > 0.5 ? 1 : 0
        });
        startTime.setDate(startTime.getDate() + 1);
      }
      return dateList;
    },
    //格式化时间
    getDate(datestr) {
      var temp = datestr.split("-");
      var date = new Date(temp[0], temp[1] - 1, temp[2]);
      return date;
    },
    //绘制折线图
    drawChart() {
      this.chart && this.chart.clear();
      this.chart = null;
      // console.log("开始绘制");
      this.chart = new F2.Chart({
        id: "myChart",
        pixelRatio: window.devicePixelRatio
      });

      this.chart.source(this.data, {
        value: {
          tickCount: 5,
          min: 0
        },
        date: {
          type: "timeCat",
          range: [0, 1],
          tickCount: 3
        }
      });
      this.chart.tooltip({
        custom: true,
        showXTip: true,
        showYTip: true,
        snap: true,
        crosshairsType: "xy",
        crosshairsStyle: {
          lineDash: [2]
        },
        xTipBackground: {
          fill: this.chartColor
        },
        yTipBackground: {
          fill: this.chartColor
        }
      });
      this.chart.axis("date", {
        label: function label(text, index, total) {
          const textCfg = {};
          if (index === 0) {
            textCfg.textAlign = "left";
          } else if (index === total - 1) {
            textCfg.textAlign = "right";
          }
          return textCfg;
        }
      });
      //   this.chart.line().position("date*value").color('value',(value)=>{
      //       if(value>80){
      //           return "#000000";
      //       }else{
      //         return '#6691FB'
      //       }
      //     });
      // this.chart
      //   .line()
      //   .position("time*score")
      //   .color(this.chartColor);
        this.chart.line().position("date*value").color('#6691FB');
      // this.chart.point()
      //     .position('date*value')
      //     .size('tag', function(val) {
      //         return val ? 3 : 0;
      //     })
      //     .style('tag', {
      //         fill: function fill(val) {
      //         if (val === 1) {
      //             return '#6691FB';
      //         }
      //         },
      //         stroke: '#fff',
      //         lineWidth: 1
      //     });
      this.chart.render();
    },
    /* 获取历史成绩 */
    async getHistoryRecord() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
        type: this.menuType
      };
      let result = await getHistoryRecord(params);
      console.log("获取历史成绩:", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          // this.data = data.map(item=>{
          //   return {
          //     ...item,
          //     score:Number(item.score),
          //     value:Number(item.score),
          //     date:item.time
          //   }
          // });


          // 获取时间段的每一天对应的数据<---
          this.data = this.chartData.map(item=>{
            let index = data.findIndex(item1=>item1.time == item.date);
            if(index != -1){
              return {
                ...item,
                value:Number(data[index].score)
              }
            }else {
              return item;
            }
          })
          // 获取时间段的每一天对应的数据--->


          this.donePaperData = [...data];
          this.donePaperData.reverse();
          this.drawChart();
        }
      }
      this.SET_IS_LOADING(false);
    },
    /* 考试回顾 */
    testReview(item) {
      this.$router.push({
        path: "/m/v2-answer-sheet",
        query: {
          type: item.paperType,
          testRecord: item.id,
          testId: item.paperId,
          review: 1
        }
      });
    },
    initPage() {
      //获取当前仅有的数据
      // this.getHistoryRecord();

      //获取每一天的数据
      this.menuHandle(1);
      // let data = this.formatEveryDay("2021-03-08", "2021-04-08");
      // console.log("时间段", data);
      // this.data = data;
      // this.getDateDay("year");
    }
  },
  created() {
    if (!this.token && Object.keys(this.user_info).length == 0) {
      this.$router.replace("/m/login");
      return;
    }
    this.initPage();
  },
  activated() {
    if (!this.token && Object.keys(this.user_info).length == 0) {
      this.$router.replace("/m/login");
      return;
    }
    this.initPage();
  },
  mounted() {
    // this.drawChart();
    // this.menuHandle('week');
  }
};
</script>

<style lang="scss" scoped>
.history-score {
  background-color: #f7f7fa;
  min-height: 100vh;
  width: 7.2rem;
  .head-charts {
    width: 7.2rem;
    background: #ffffff;
    .charts-title {
      font-size: 0.3072rem;
      padding: 0.288rem;
      color: #313233;
    }
    .charts-menu {
      padding: 0 0.288rem;
      display: flex;
      .menu-item {
        font-size: 0.2304rem;
        color: var(--theme-color);
        width: 1.152rem;
        height: 0.384rem;
        line-height: 0.384rem;
        text-align: center;
        background-color: #fff;
        border-radius: 0.192rem;
        margin-right: 0.3072rem;
        border: solid 0.0192rem var(--theme-color);
        &.selected {
          background-color: var(--theme-color);
          color: #ffffff;
        }
      }
    }
  }
  .test-record {
    margin-top: 0.192rem;
    background-color: #ffffff;
    //   padding: .288rem 0rem .288rem .288rem;
    padding-left: 0.288rem;
    padding-bottom: 0.288rem;
    .record-item {
      height: 0.9984rem;
      width: 6.912rem;
      border-bottom: 0.026rem solid #f7f7fa;
      display: flex;
      padding-right: 0.2rem;
      justify-content: space-between;
      align-items: center;
      // font-size: .2304rem;
      font-size: 0.25rem;
      .record-time {
        color: #adafb3;
      }
      .record-fraction {
        color: #4a4b4d;
      }
      .record-status {
        display: inline-block;
        width: 1rem;
        text-align: center;
      }
      .record-review {
        color: #949699;
        display: flex;
        align-items: center;
        img {
          width: 0.2304rem;
          height: 0.2304rem;
          display: block;
          margin-left: 0.1rem;
        }
      }
      &:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>
